package cn.tedu.charging.device.dao.impl;

import cn.tedu.charging.device.dao.repository.StationCacheTemplateRepository;
import cn.tedu.charging.device.pojo.po.StationCanalPO;
import cn.tedu.charging.device.pojo.po.StationInfoWrapper;
import cn.tedu.charging.device.pojo.po.StationPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 位置信息和基本信息建议分开存  基本信息可以复用
 *
 * 基本信息 可以通过什么类型存 ? 更加合理
 * String
 * Hash独享 一个站 一个hash
 * Hash共享 所有站 一个hash
 *
 *
 *
 */
@Slf4j
@Repository("GEOANDSTRING")
public class StationCacheTemplateGEOAndStringImpl
        extends AbstractStationCacheTemplate
        implements StationCacheTemplateRepository {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void save(List<StationPO> stationPOS) {
        saveGEOByRedisGEOAndMemberIsId(stationPOS);
        saveStationInfoByString(stationPOS);
    }

    private void saveStationInfoByString(List<StationPO> stationPOS) {
        Map<String,StationPO> stationPOMap = new HashMap<>();
        for (StationPO stationPO : stationPOS) {
            String key = "station_info_str_" + stationPO.getId();
            stationPOMap.put(key,stationPO);
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.multiSet(stationPOMap);
    }


    public List<StationInfoWrapper> search(Double longitude, Double latitude, Double distance) {
        return super.search(longitude,latitude,distance);
    }

    @Override
    public void delete(StationCanalPO stationCanalPO) {
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.remove("stations",stationCanalPO.getId());

        redisTemplate.delete("station_info_str_" + stationCanalPO.getId());
    }

    @Override
    public void add(StationCanalPO stationCanalPO) {
        log.debug("加点");
        BoundGeoOperations stations = redisTemplate.boundGeoOps("stations");
        Point point = new Point(Double.valueOf(stationCanalPO.getStationLng().toEngineeringString()),
                Double.valueOf(stationCanalPO.getStationLat().toEngineeringString()));
        stations.add(point,stationCanalPO.getId());

        log.debug("加string");
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("station_info_str_" + stationCanalPO.getId(),stationCanalPO);
    }

    @Override
    public StationPO getStationInfoById(String stationId) {
        String key = "station_info_str_" + stationId;
        ValueOperations<String,StationPO> valueOperations
                = redisTemplate.opsForValue();
        return valueOperations.get(key);
    }

    @Override
    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }
}
